import axios from 'axios'
import store from '@/store'
import router from '@/router'

import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const service = axios.create({
   baseURL: import.meta.env.VITE_ADMIN_BASE_URL,
   timeout: 5000
})

// 前置拦截
service.interceptors.request.use((config) => {
   // 进度条开始
   NProgress.start()
   if (store.getters.token) {
      // 添加token信息
      config.headers['Authorization'] = store.getters.token
   }
   return config
}, (error) => {
   return Promise.reject(error)
})
// 后置拦截
service.interceptors.response.use(
   (response) => {
      const res = response.data
      // 正常状态 => 进度条结束
      NProgress.done()
      if (res.code != 200) {
         ElMessage.error(res.msg)
         return Promise.reject(new Error(res.msg))
      } else {
         return res
      }
   },
   (error) => {
      // 异常状态 => 进度条结束
      NProgress.done()
      console.log(error)
      let { status, data } = error.response // 解构数据
      if (status === 401) {
         // 清空管理员个人信息
         store.dispatch('logout')
         // 跳转到登录页面
         router.push({ path: '/login' })
      } else {
         error.response && ElMessage.error(data.msg)
      }

      return Promise.reject(error)
   }
)
export default service